package org.hope.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hope.handlers.ServiceHandler;
import org.hope.result.Hotel;
import org.hope.result.RefineCriteria;
import org.hope.result.Result;
import org.hope.service.HopeSmartService;
import org.hope.util.Constants;

/**
 * @author Thilanka
 */
public class SearchResultsController extends HttpServlet
{
	
	private static final long serialVersionUID = 5503843585010430818L;
	
	private final static String SEARCH_TEXT = "SEARCH_TEXT";
	private final static String ALL = "ALL";

	@Override
	protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
	{
		String searchText = req.getParameter( "searchText" );
		String selectedOption = ALL;
		
		if ( searchText == null )
		{
			searchText = ( String ) req.getSession().getAttribute( SEARCH_TEXT );
			int numberOfCriterias = Integer.parseInt( req.getParameter( "numCriteria" ) );

			for ( int i = 0; i < numberOfCriterias; i++ )
			{
				String filterOption = req.getParameter( Constants.FILTER + Constants.FILTER_SEPERATOR + i );
				if ( filterOption != null && filterOption.length() > 0 )
				{
					searchText += ( " " + filterOption );
					selectedOption = filterOption;
				}
			}
		}
		else
		{
			// set the searchtext to session
			req.getSession().setAttribute( SEARCH_TEXT, searchText );
		}

		HopeSmartService hopeSmartService = ServiceHandler.getHopeSmartService();
		List<Result> results = hopeSmartService.search( searchText );

		List<Hotel> hotels = new ArrayList<Hotel>();
		List<RefineCriteria> criterias = new ArrayList<RefineCriteria>();
		for ( Result result : results )
		{
			if ( result.getResultType() == Result.RESULT_TYPE_HOTEL )
			{
				hotels.add( ( Hotel ) result );
			}
			else if ( result.getResultType() == Result.RESULT_TYPE_CRITERA )
			{
				criterias.add( ( RefineCriteria ) result );
			}
		}

		req.setAttribute( "results", hotels );
		req.setAttribute( "criterias", criterias );
		req.setAttribute( "selectedOption", selectedOption );

		req.getRequestDispatcher( "jsp/searchResults.jsp" ).forward( req, resp );
	}

	@Override
	protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
	{
		doGet( req, resp );
	}

}
